package fair.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import fair.dao.CheckGroupDao;
import fair.entity.PageResult;
import fair.pojo.CheckGroup;
import fair.pojo.CheckItem;
import fair.service.CheckGroupService;
import fair.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fair_wu
 * @version v1.0
 * @date 2021-01-24 下午 23:16
 */

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao dao;

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> page = dao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void add(CheckGroup group, Integer[] ids) {
        dao.add(group);
        setCheckGroupAndCheckItem(group.getId(), ids);
    }

    private void setCheckGroupAndCheckItem(Integer groupId, Integer[] ids) {
        if (ids != null && ids.length > 0) {
            Map<String, Integer> map = null;
            for (Integer id : ids) {
                map = new HashMap<>();
                map.put("checkgroup_id", groupId);
                map.put("checkitem_id", id);
                dao.setCheckGroupAndCheckItem(map);
            }
        }
    }

    @Override
    public CheckGroup findById(Integer id) {
        return dao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdByCheckGroupId(Integer id) {
        return dao.findCheckItemIdByCheckGroupId(id);
    }

    @Override
    public void edit(CheckGroup group, Integer[] checkitemIds) {
        dao.edit(group);
        dao.deleteCheckItemIdByCheckGroupId(group.getId());
        setCheckGroupAndCheckItem(group.getId(), checkitemIds);
    }

    @Override
    public void deleteById(Integer id) {
        long count = dao.findCountByCheckGroupId(id);
        if (count > 0) {
            throw new RuntimeException("当前检查项被引用，无法删除");
        }
        dao.deleteCheckItemIdByCheckGroupId(id);
        dao.deleteById(id);
    }

    @Override
    public List<CheckGroup> findAll() {
        return dao.findAll();
    }
}
